

interface StorageCache {
    set(key: string | null, value: string | null): void;
    get(key: string | null): string | null;
    setJSON(key: string | null, jsonValue: any | null): void;
    getJSON(key: string | null): any | null;
    remove(key: string): void;
}
const sessionCache :StorageCache = {
    set (key:string|null, value:string|null):void {
        if (!sessionStorage) {
            return
        }
        if (key != null && value != null) {
            sessionStorage.setItem(key, value)
        }
    },
    get (key:string|null):string|null {
        if (!sessionStorage) {
            return null
        }
        if ( key == null) {
            return null
        }
        return sessionStorage.getItem(key)
    },
    setJSON (key:string|null, jsonValue:string|null):void {
        if (jsonValue != null) {
            this.set(key, JSON.stringify(jsonValue))
        }
    },
    getJSON (key:string|null): any | null  {
        const value = this.get(key)
        if (value != null) {
            return JSON.parse(value)
        }
    },
    remove (key:string):void {
        sessionStorage.removeItem(key);
    }
}
const localCache:StorageCache = {
    set (key:string|null, value:string|null):void {
        if (!localStorage) {
            return
        }
        if (key != null && value != null) {
            localStorage.setItem(key, value)
        }
    },
    get (key:string|null):string|null {
        if (!localStorage) {
            return null
        }
        if (key == null) {
            return null
        }
        return localStorage.getItem(key)
    },
    setJSON (key:string|null, jsonValue:string|null): void {
        if (jsonValue != null) {
            this.set(key, JSON.stringify(jsonValue))
        }
    },
    getJSON (key:string|null): any | null {
        const value = this.get(key)
        if (value != null) {
            return JSON.parse(value)
        }
    },
    remove (key:string):void {
        localStorage.removeItem(key);
    }
}

export default {
    /**
     * 会话级缓存
     */
    session: sessionCache,
    /**
     * 本地缓存
     */
    local: localCache
}
